package com.fxm.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxm.constant.RedisConstants;
import com.fxm.dao.QuestionMapper;
import com.fxm.domain.Option;
import com.fxm.domain.Question;
import com.fxm.domain.Rule;
import com.fxm.returns.RespCode;
import com.fxm.returns.RespEntity;
import com.fxm.service.QuestionService;
import com.fxm.service.RuleService;
import com.fxm.utils.RedisUtil;
import com.fxm.vo.param.OpenParam;
import com.fxm.vo.param.QuestionParam;
import com.fxm.vo.result.AnswerResult;
import com.fxm.vo.result.QuestionResult;
import com.fxm.vo.result.RuleResult;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 答题 服务实现类
 * </p>
 *
 * @author fxm
 * @since 2021-01-07
 */
@Slf4j
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RuleService ruleService;

    @Override
    public RespEntity<Integer> getAllIntegral() {
        Integer integral = 0;
        List<Question> questionList = questionMapper.listAllQuestions();
        for (Question question : questionList) {
            integral += question.getIntegralValue();
        }
        log.info("今日答题本日可共获得积分，integral={}", integral);
        return new RespEntity(RespCode.SUCCESS, integral);
    }

    @Override
    public RespEntity<RuleResult> getQuestionRule(OpenParam openParam) {
        QueryWrapper<Rule> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Rule::getOpenid, openParam.getOpenid())
                .eq(Rule::getDeleted, 0);
        Rule rule = ruleService.getOne(queryWrapper);
        RuleResult ruleResult = new RuleResult();
        ruleResult.setLimit(rule.getRule());
        return new RespEntity(RespCode.SUCCESS, ruleResult);
    }

    @Override
    public RespEntity<QuestionResult> getQuestionInit() {
        List<Question> questionList = questionMapper.listAllQuestions();
        //创建题目缓存
        createCache(questionList);
        //题目初始化 第一题
        QuestionResult questionResult = dataMapping("1");
        //题目数量
        questionResult.setQuestionNumber(questionList.size());
        return new RespEntity(RespCode.SUCCESS, questionResult);
    }

    @Override
    public RespEntity<QuestionResult> getNextQuestion(QuestionParam questionParam) {
        if (Objects.isNull(questionParam)) {
            log.info("参数为空");
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }
        QuestionResult questionResult = dataMapping(questionParam.getQuestionId());
        return new RespEntity(RespCode.SUCCESS, questionResult);
    }

    @Override
    public RespEntity<Integer> getChallengeNumbers(OpenParam openParam) {
        if (Objects.isNull(openParam)) {
            log.info("参数为空");
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }
        QueryWrapper<Rule> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Rule::getOpenid, openParam.getOpenid())
                .eq(Rule::getDeleted, 0);
        Rule rule = ruleService.getOne(queryWrapper);
        Integer challenge = rule.getChallenge();
        log.info("今日答题剩余挑战次数为：challenge={}", challenge);
        return new RespEntity(RespCode.SUCCESS, challenge);
    }

    @Override
    public RespEntity updateChallengeNum(OpenParam openParam) {
        if (Objects.isNull(openParam)) {
            log.info("参数为空");
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }
        QueryWrapper<Rule> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Rule::getOpenid, openParam.getOpenid())
                .eq(Rule::getDeleted, 0);
        Rule rule = ruleService.getOne(queryWrapper);
        Integer challenge = rule.getChallenge();
        if (challenge > 0) {
            challenge -= 1;
            rule.setChallenge(challenge);
            ruleService.updateById(rule);
            log.info("剩余挑战次数为，challenge={}", challenge);
        }
        return new RespEntity(RespCode.SUCCESS);
    }

    /**
     * 创建题目缓存
     * @param questionList
     */
    private void createCache(List<Question> questionList) {
        for (int i = 0; i < questionList.size(); i++) {
            String index = String.valueOf(i+1);
            String question = JSONUtil.toJsonStr(questionList.get(i));
            redisUtil.hset(RedisConstants.key.QUESTION_ALL, index, question);
        }
    }

    /**
     * 数据映射
     * @param id
     * @return
     */
    private QuestionResult dataMapping(String id) {
        QuestionResult questionResult = new QuestionResult();
        String ques = redisUtil.hget(RedisConstants.key.QUESTION_ALL, id);
        log.info("第"+ id +"题，题目是，object={}", ques);
        if (StringUtils.isNotBlank(ques)) {
            Question question = JSONUtil.toBean(ques, Question.class);
            questionResult.setQuestionId(question.getId());
            questionResult.setType(question.getQuestionType());
            questionResult.setQuestion(question.getQuestionTitle());
            questionResult.setIntegral(question.getIntegralValue());
            List<AnswerResult> answerResultList = Lists.newArrayList();
            for (Option option : question.getOptionList()) {
                String optionContent = option.getOptionType() + "：" + option.getOptionContent();
                if (StringUtils.equals(option.getOptionType(), question.getQuestionAnswer())) {
                    answerResultList.add(new AnswerResult(optionContent, true));
                }else {
                    answerResultList.add(new AnswerResult(optionContent, false));
                }
            }
            questionResult.setAnswer(answerResultList);
        }
        return questionResult;
    }


}
